<?php
  include('../includes.php');
  
  $membership = New Membership();
  $membership->confirm_admin();

  $agenda = new Agenda();
  $week   = $agenda->current_week;
  $vorig_week  = max($week - 3, 0);

  $jaar   = $agenda->year;
  $vorig_jaar = $jaar - 1;

  $delete_previous_year = mysql_query('SELECT ID FROM '.DB_LES.' WHERE jaar="'.$vorig_jaar.'"');

  while ($row = mysql_fetch_assoc($delete_previous_year))
    mysql_query('DELETE FROM '.DB_DEELNEMER.' WHERE les_ID="'.$row['ID'].'"');

  mysql_query('DELETE FROM '.DB_LES.' WHERE jaar="'.$vorig_jaar.'"');

  for ($i = 0; $i <= $vorig_week; $i++)
  {
    $delete_previous_week = mysql_query('SELECT ID FROM '.DB_LES.' WHERE jaar="'.$jaar.'" AND week="'.$i.'"');

    while ($row = mysql_fetch_assoc($delete_previous_week))
      mysql_query('DELETE FROM '.DB_DEELNEMER.' WHERE les_ID="'.$row['ID'].'"');

    mysql_query('DELETE FROM '.DB_LES.' WHERE jaar="'.$jaar.'" AND week="'.$i.'"');
  }

  $all_lessen = array();
  $lessen_with_leden = array();

  $select_all_lessen   = mysql_query('SELECT ID FROM '.DB_LES);
  $delete_empty_lessen = mysql_query('SELECT DISTINCT '.DB_LES.'.ID FROM '.DB_LES.' INNER JOIN '.DB_DEELNEMER.' ON ('.DB_DEELNEMER.'.les_ID = '.DB_LES.'.ID) WHERE '.DB_DEELNEMER.'.user_ID > 0');

  while ($row = mysql_fetch_assoc($select_all_lessen))
    $all_lessen[] = $row['ID'];

  while ($row = mysql_fetch_assoc($delete_empty_lessen))
    $lessen_with_leden[] = $row['ID'];

  foreach ($all_lessen as $les_id)
    if (! in_array($les_id, $lessen_with_leden))
      mysql_query('DELETE FROM '.DB_LES.' WHERE ID="'.$les_id.'"');

  $url = BASE_URL;
  header("Location: $url/admin/");
?>